//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package events_subscribe

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"time"

	"atomgit.com/openlinksaas/api-server/dao/event_dao"
	"atomgit.com/openlinksaas/proto-gen-go.git/events_subscribe_api"
)

func sendChatMsg(msg string, subItem *event_dao.SubscribeInfoDbItem) error {
	if subItem.ChatBotType == uint32(events_subscribe_api.CHAT_BOT_TYPE_CHAT_BOT_QYWX) {
		return sendToQywx(msg, subItem.ChatBotAddr)
	} else if subItem.ChatBotType == uint32(events_subscribe_api.CHAT_BOT_TYPE_CHAT_BOT_DING) {
		return sendToDing(msg, subItem.ChatBotAddr, subItem.ChatBotSignCode)
	} else if subItem.ChatBotType == uint32(events_subscribe_api.CHAT_BOT_TYPE_CHAT_BOT_FS) {
		return sendToFs(msg, subItem.ChatBotAddr, subItem.ChatBotSignCode)
	}
	return nil
}

type QywxMsgText struct {
	Content string `json:"content"`
}

type QywxMsg struct {
	MsgType string      `json:"msgtype"`
	Text    QywxMsgText `json:"text"`
}

// 发送到企业微信
func sendToQywx(msg, addr string) error {
	data, err := json.Marshal(&QywxMsg{
		MsgType: "text",
		Text: QywxMsgText{
			Content: msg,
		},
	})
	if err != nil {
		return err
	}
	res, err := http.Post(addr, "application/json", bytes.NewBuffer(data))
	if err != nil {
		return err
	}
	defer res.Body.Close()

	return nil
}

type DingMsgText struct {
	Content string `json:"content"`
}

type DingMsg struct {
	MsgType string      `json:"msgtype"`
	Text    DingMsgText `json:"text"`
}

// 发送到钉钉
func sendToDing(msg, addr, sec string) error {
	nowTime := time.Now().UnixNano() / 1e6
	toSignStr := fmt.Sprintf("%d\n%s", nowTime, sec)
	h := hmac.New(sha256.New, []byte(sec))
	h.Write([]byte(toSignStr))
	signStr := base64.StdEncoding.EncodeToString(h.Sum(nil))

	data, err := json.Marshal(DingMsg{
		MsgType: "text",
		Text: DingMsgText{
			Content: msg,
		},
	})
	if err != nil {
		return err
	}

	req, err := http.NewRequest("POST", addr+fmt.Sprintf("&timestamp=%d&sign=%s", nowTime, url.QueryEscape(signStr)), bytes.NewBuffer(data))
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "application/json; charset=utf-8")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	// data, err = io.ReadAll(res.Body)
	// if err != nil {
	// 	return err
	// }
	// fmt.Println(string(data))
	return nil
}

type FsMsgContent struct {
	Text string `json:"text"`
}

type FsMsg struct {
	Timestamp string       `json:"timestamp"`
	Sign      string       `json:"sign"`
	MsgType   string       `json:"msg_type"`
	Content   FsMsgContent `json:"content"`
}

// 发送到飞书
func sendToFs(msg, addr, sec string) error {
	nowTime := time.Now().Unix()
	toSignStr := fmt.Sprintf("%v\n%s", nowTime, sec)
	h := hmac.New(sha256.New, []byte(toSignStr))
	signStr := base64.StdEncoding.EncodeToString(h.Sum(nil))

	data, err := json.Marshal(FsMsg{
		Timestamp: fmt.Sprint(nowTime),
		Sign:      signStr,
		MsgType:   "text",
		Content: FsMsgContent{
			Text: msg,
		},
	})
	if err != nil {
		return err
	}
	req, err := http.NewRequest("POST", addr, bytes.NewBuffer(data))
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "application/json; charset=utf-8")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	// data, err = io.ReadAll(res.Body)
	// if err != nil {
	// 	return err
	// }
	// fmt.Println(string(data))
	return nil
}
